import axios from "axios";
// @ts-ignore
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken,serverUrl } from "./tools";

// 约定大于配置


const instance = axios.create({
  baseURL: serverUrl,
  timeout: 5000,
});

// Add a request interceptor
// 请求拦截，发起请求之前执行
instance.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    NProgress.start(); // 启动进度条
    // @ts-ignore
    config.headers["token"] = getToken();
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
// 响应拦截，返回数据之后执行
instance.interceptors.response.use(
  function (response) {
    NProgress.done();
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  },
  function (error) {
    NProgress.done();
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  }
);

/**
 * 发起get请求
 * @param url     请求地址
 * @param params  url中传递的数据
 * @returns
 */
export const get = (url: string, params: any = {}) =>
  instance.get(url, { params }).then((res) => res.data);

/**
 * post请求
 * @param url
 * @param data
 * @returns
 */
export const post = (url: string, data: any) =>
  instance.post(url, data).then((res) => res.data);

/**
 * put请求
 * @param url
 * @param data
 * @returns
 */
export const put = (url: string, data: any) =>
  instance.put(url, data).then((res) => res.data);

/**
 * delete请求
 * @param url
 * @returns
 */
export const del = (url: string) =>
  instance.delete(url).then((res) => res.data);
